package dev.entao.core

import dev.entao.base.base64Encoded
import dev.entao.core.render.sendBack
import dev.entao.sql.ConnLook
import kotlin.reflect.full.hasAnnotation

//config -> create ----> [service loop] --> destroy
abstract class SweetApp(val httpService: HttpService) {

    abstract val appName: String

    open fun onConfig() {}

    open fun onCreate() {}
    open fun beforeService(context: HttpContext) {}

    open fun afterService(context: HttpContext) {}

    open fun onCleanThreadLocal() {
        ConnLook.cleanThreadConnections()
    }

    open fun onDestroy() {}



    open fun needAuth(context: HttpContext, code: Int = 401, msg: String = "") {
        val loginUri: String = httpService.findRouter { it.function.hasAnnotation<LoginWebAction>() }?.uri ?: ""
        if (context.acceptHtml && loginUri.isNotEmpty() && context.request.referer != null) {
            var url = context.request.requestURI
            val qs = context.request.queryString ?: ""
            if (qs.isNotEmpty()) {
                url = "$url?$qs"
            }
            url = url.base64Encoded
            context.sendBack {
                setParam(Sweet.BACK_URL, url)
            }
            return
        }
        context.sendError(code, msg)
    }
}
